package com.knife.service;

import java.io.File;
import java.io.Serializable;

import com.knife.web.Globals;

public class BackGroundTask implements Runnable, Serializable{
	/**
	 * 
	 */
	private static final long serialVersionUID = 2968920554464551733L;
	protected String name;
    protected int counter;
    protected int total;
    protected int sum;
    private boolean started;
    private boolean running;
    protected int sleep;
    
    public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public int getCounter() {
		return counter;
	}

	public void setCounter(int counter) {
		this.counter = counter;
	}

	public int getTotal() {
		return total;
	}

	public void setTotal(int total) {
		this.total = total;
	}

	public BackGroundTask(){
        counter = 0;
        total = 100;
        sum = 0;
        started = false;
        running = false;
        sleep = 100;
    }

    protected void work() {
        try {
            Thread.sleep(sleep);
            counter++;
            sum += counter;
        } catch (InterruptedException e) {
            setRunning(false);
        }
    }

    public synchronized int getPercent() {
    	float p=counter*100/total;
        return (int)p;
    }

    public synchronized boolean isStarted() {
        return started;
    }

    public synchronized boolean isCompleted() {	
        return counter == total;
    }

    public synchronized boolean isRunning() {
        return running;
    }

    public synchronized void setRunning(boolean running) {
        this.running = running;
        File lock=new File(Globals.APP_BASE_DIR+"/html/gen.lock");
        if (running){
        	if(!lock.exists()){
        		try{
        			lock.createNewFile();
        			started = true;
        		}catch(Exception e){
        			System.out.println("can't create lock file,it may cause generate error,info:"+e.getMessage());
        		}
        	}else{
        		started = true;
            }
        }else{
        	if(lock.exists()){
        		lock.delete();
        	}
        }
    }

    public synchronized Object getResult() {
        if (isCompleted())
            return new Integer(sum);
        else
            return null;
    }

    public void run() {
        try {
            setRunning(true);
            while (isRunning() && !isCompleted()){
                work();
            }
        } finally {
            setRunning(false);
        }
    }

}
